<template>
    <div>
      <a-drawer :maskClosable="false" width="1100"  :visible="dialogData.show" direction="rtl"  @close="handleClose">
        <div slot="title">
          <i style="cursor: pointer" v-if="dialogData.type == 'tranes'" class="el-icon-arrow-left" @click="handleBack"></i>
          <span>{{dialogData.title}}</span>
        </div>
        <el-row v-loading="loading" style="width:1120px;padding-bottom:150px;height:100%;overflow-y:auto">
          <el-col :span="18">
             <el-form :model="parames" size="small" :rules="rules" label-position="left" ref="parames" label-width="94px" class="addForm">
                <el-row style="padding: 0 40px" :gutter="20">
                  <a-collapse :defaultActiveKey="activeNames" :bordered="false">
                    <a-collapse-panel class="marginB10" header="基本信息" key="1">
                      <el-col :span="24" style="margin-top:15px">
                          <el-row :gutter="20">
                            <el-col :span="12">
                              <el-form-item label="合同状态:">
                                <el-select style="width:100%" size="small"  v-model="parames.contractStatus" placeholder="请选择">
                                  <el-option v-for="(item,index) in contractStatusData" :key="index" :label="item.desc" :value="item.name"></el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                              <el-form-item label="公司名称:" prop="customerId">
                                <el-select style="width:100%" size="small" filterable @change="changeCustomer"  v-model="parames.customerId" placeholder="请选择">
                                  <el-option v-for="(item,index) in kehuData" :key="index" :label="item.customerName" :value="item.id"></el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                              <el-form-item label="企业类型:">
                                <el-select style="width:100%" size="small"  v-model="parames.enterpriseType" placeholder="请选择">
                                  <el-option v-for="(item,index) in companyData" :key="index" :label="item.desc" :value="item.name"></el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                              <el-form-item label="是否开票:">
                                <el-select style="width:100%" size="small"  v-model="parames.invoice" placeholder="请选择">
                                  <el-option label="是" :value="true"></el-option>
                                  <el-option label="否" :value="false"></el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                              <el-form-item label="开票张数:" prop="invoicingCount">
                                <el-input size="small" v-model="parames.invoicingCount" placeholder="请输入"></el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="12">
                              <el-form-item label="开票额度:" prop="totalInvoice">
                                <el-input size="small" v-model="parames.totalInvoice" placeholder="请输入"></el-input>
                              </el-form-item>
                            </el-col>
                            
                          </el-row>
                      </el-col>
                      <el-col :span="24">
                        <el-row :gutter="20">
                          <el-col :span="12">
                              <el-form-item label="联系人:" prop="contacts">
                                <el-input size="small" v-model="parames.contacts" placeholder="请输入"></el-input>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="联系电话:" prop="contactMobile">
                                <el-input size="small" v-model="parames.contactMobile" placeholder="请输入"></el-input>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="法人:" prop="artificialPerson">
                                <el-input size="small" v-model="parames.artificialPerson" placeholder="请输入"></el-input>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="法人电话:" prop="artificialPersonMobile">
                                <el-input size="small" v-model="parames.artificialPersonMobile" placeholder="请输入"></el-input>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="联系方式:" prop="">
                              <el-row >
                                <el-col :span="8">
                                  <el-select size="small" v-model="parames.contactType" placeholder="请选择">
                                    <el-option v-for="(item,index) in contactType" :key="index" :label="item.desc" :value="item.name"></el-option>
                                  </el-select>
                                </el-col>
                                <el-col :span="16">
                                  <el-input size="small" v-model="parames.contactDetails" placeholder="请输入"></el-input>
                                </el-col>
                              </el-row>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="合同来源:" prop="contractSourceType" >
                            <shangJi v-model="parames.contractSourceId" @checkValue="checkValue" :typeid="parames.contractSourceType" :id="parames.contractSourceId" :type="dialogData.type"></shangJi>
                          </el-form-item>
                      </el-col>
        
                      <el-col :span="24">
                        <el-row :gutter="20">
                          <el-col :span="12">
                              <el-form-item label="销售代表:" prop="sellerId">
                                <userTree v-model="parames.sellerId" :currentValue="parames.sellerId"></userTree>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="会计:" prop="accountantId">
                                <userTree v-model="parames.accountantId" :currentValue="parames.accountantId"></userTree>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                              <el-form-item label="办理人:" prop="handlerId">
                                <userTree v-model="parames.handlerId" :currentValue="parames.handlerId"></userTree>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="签约日期:" prop="signingDate">
                                <el-date-picker
                                style="width:100%"
                                v-model="parames.signingDate"
                                type="date"
                                placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="20">
                          <el-col :span="12">
                            <el-form-item label="合同开始日期:">
                                <el-date-picker
                                style="width:100%"
                                v-model="parames.startDate"
                                type="date"
                                placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                          </el-col>
                          <el-col :span="12">
                            <el-form-item label="合同结束日期:">
                                <el-date-picker
                                style="width:100%"
                                v-model="parames.endDate"
                                type="date"
                                placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                          </el-col>
                        </el-row>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="合同备注:">
                          <el-input size="small" type="textarea" v-model="parames.contractRemark" placeholder="请输入"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="16">
                        <el-form-item label="合同原件:">
                          <el-upload
                            class="upload-demo"
                            multiple
                            :headers="myHeaders"
                            :action="fileAction"
                            :on-success="handleSucess"
                            :on-remove="handleRemove"
                            :file-list="file">
                            <el-button icon="el-icon-upload2" type="primary" plain style="width: 400px">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">建议单个文件不超过50M</div>
                          </el-upload>
                        </el-form-item>
                      </el-col>
                    </a-collapse-panel>
                    <a-collapse-panel class="marginB10" header="产品列表" key="2">
                      <el-col :span="24" style="margin-top:14px">
                        <el-form-item label="快速添加:" prop="name">
                          <el-tag style="margin-right:5px;cursor:pointer" :class="item.isSelect?'tab-cur':''" v-for="(item,index) in groupListta" @click.native="handleTags(item,index)" :key="index" :type="item.isSelect?'':'info'" effect="plain" size="medium">{{item.groupName}}</el-tag>
                        </el-form-item>
                        <el-table
                          :data="parames.contractProductList"
                          show-summary
                          :summary-method="getSummaries"
                          style="width: 100%">
                          <el-table-column
                            type="index"
                            label="序号"
                            width="50">
                          </el-table-column>
                          <el-table-column
                            prop="productName"
                            label="产品名称"
                            width="100">
                          </el-table-column>
                          <el-table-column label="产品价格">
                              <template slot-scope="scope">
                                  <span>{{scope.row.lowerPriceLimit}}-{{scope.row.upperPriceLimit}}</span>
                              </template>
                          </el-table-column>
                          <el-table-column
                            width="80"
                            prop="count"
                            label="数量">
                            <template slot-scope="scope">
                              <el-form-item
                                style="margin-bottom: 0"
                                :prop="'contractProductList.' + scope.$index + '.count'"
                                label-width="0"
                                :rules="[
                                  { required: true, message: '不能为空', trigger: ['blur', 'change'] },
                                  { type: 'number', message: '请输入正整数', trigger: ['blur', 'change'] }
                                ]"
                              >
                                <span v-if="scope.row.productServiceType">
                                  <el-input :disabled="scope.row.productServiceType.name == 'DISPOSABLE'" v-model.number="scope.row.count" size="small"></el-input>
                                </span>
                              </el-form-item>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="giftCount"
                            label="赠送数量">
                            <template slot-scope="scope">
                              <el-form-item
                                style="margin-bottom: 0"
                                :prop="'contractProductList.' + scope.$index + '.giftCount'"
                                label-width="0"
                                :rules="[
                                  { required: true, message: '不能为空', trigger: ['blur', 'change'] },
                                  { type: 'number', message: '请输入正整数', trigger: ['blur', 'change'] }
                                ]"
                              >
                                <span v-if="scope.row.productServiceType">
                                  <el-input :disabled="scope.row.productServiceType.name == 'DISPOSABLE'" v-model.number="scope.row.giftCount" size="small"></el-input>
                                </span>
                              </el-form-item>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="unitPrice"
                            label="单价(元)">
                            <template slot-scope="scope">
                              <el-form-item
                                style="margin-bottom: 0"
                                :prop="'contractProductList.' + scope.$index + '.unitPrice'"
                                label-width="0"
                                :rules="[
                                  { required: true, message: '不能为空', trigger: ['blur', 'change'] },
                                  { type: 'number', message: '请输入正整数', trigger: ['blur', 'change'] }
                                ]"
                              >
                                <el-input v-model.number="scope.row.unitPrice" size="small"></el-input>
                              </el-form-item>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="discount"
                            width="100"
                            label="优惠(元)">
                            <template slot-scope="scope">
                              <el-form-item
                                style="margin-bottom: 0"
                                :prop="'contractProductList.' + scope.$index + '.discount'"
                                label-width="0"
                                :rules="[
                                  { required: true, message: '不能为空', trigger: ['blur', 'change'] },
                                  { type: 'number', message: '请输入正整数', trigger: ['blur', 'change'] },
                                ]"
                              >
                                <el-input v-model.number="scope.row.discount" size="small"></el-input>
                              </el-form-item>
                            </template>
                          </el-table-column>
                          <el-table-column label="小计">
                              <template slot-scope="scope">
                                  <span>{{scope.row.count*scope.row.unitPrice-scope.row.discount}}</span>
                              </template>
                          </el-table-column>
                          <el-table-column
                            prop="address"
                            label="操作">
                            <template slot-scope="scope">
                              <el-button size="mini" type="text" icon="el-icon-delete" @click.native="handleDelproduct(scope.$index,scope.row)"></el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                        <el-button icon="el-icon-plus" @click="handelAddProduct" size="small" style="width:100%;margin-top:20px">添加产品</el-button>
                      </el-col>
                    </a-collapse-panel>
                  </a-collapse>
                </el-row>
            </el-form>
          </el-col>
          <el-col :span="5" style="position: fixed;top:80px;right:-10px;width:240px">
          <div class="form-team-box">
            <div v-if="dialogData.type == 'edit'">
              <el-button
                @click="handleCancle"
                size="small"
                icon="el-icon-close"
                style="width:200px;text-align: left;margin-bottom:10px"
              >取消编辑</el-button>
            </div>
            <p class="formtitle" v-if="parames.userIdList">团队成员（{{parames.userIdList.length}}）人</p>
            <el-row style="margin-top: 10px">
              <span v-for="(item,index) in parames.userIdList" :key="index">
                <el-col style="margin-bottom:10px" v-if="index==0" >
                  <span class="team-icon" style="background: #409efe" v-if="item.userName">{{item.userName.slice(0,1)}}</span>
                  <span class="team-name">{{item.userName}}</span>
                </el-col>
                <el-col style="margin-bottom:10px" v-if="index>0" >
                  <span class="team-icon" style="background: #409efe" v-if="item.userName">{{item.userName.slice(0,1)}}</span>
                  <span class="team-name">{{item.userName}}</span>
                  <i class="el-icon-delete team-del" @click="handleDeleteUser(index,item)"></i>
                </el-col>
              </span>
            </el-row>
            <el-button @click="handleNewTeam" type="text" style="margin-top:14px" icon="el-icon-plus">添加新成员</el-button>
          </div>
        </el-col>
        </el-row>
        
        <div class="from-bottom-box">
          <el-button size="small" :loading="loading" type="primary" @click="handleSave">保存</el-button>
          <!-- <el-button size="small" v-if="dialogData.type == 'new'">直接签订</el-button> -->
          <el-button size="small" @click="handleClose">取消</el-button>
        </div>
      </a-drawer>
      <productDialog :productData="productData" @watchSlect="watchSlect"></productDialog>
      <teamDialog :teamData="teamData" @selectUser="selectUser"></teamDialog>
    </div>
</template>

<script>
import productDialog from '../opportunityManage/productDialog'

export default {
    props: ['dialogData'],
    data() {
        return {
          activeNames: ['1','2'],
          loading: false,
          parames: {
            id: '',
            // contractNumber: '', //合同编号,
            customerId: '', //客户id
            contacts: '', //联系人,
            contractStatus: 'PENDING', //合同状态-新建为待签订,
            contractType: '', //合同类型,
            // contractAmount: '', 
            enterpriseType: '', //企业类型
            contactType: '', //联系方式类型
            contactDetails: '', //联系
            partyA: '', //甲方,
            partyB: '', //乙方,
            opportunity: '',//关联商机,
            contractSourceType: '',
            contractSourceId: '', //来源id
            sellerId: '',//销售代表,
            signingDate: '', //签约日期
            contractRemark: '',//合同备注,
            opportunityId: '', //商机id
            invoice: false, //是否开发票
            startDate:'',//合同开始日期
            endDate:'',//合同结束日期
            contactMobile: '',//联系电话
            artificialPerson: '', //法人
            artificialPersonMobile: '', //法人电话
            accountantId: '',//会计ID
            handlerId: '', //办理人ID
            renew: false, //是否是续签
            attachmentSet: [],//合同原件URL,
            contractProductList: [], //产品列表
            userIdList: [],
            invoicingCount: '',//开票张数
            totalInvoice: '',//开票额度
          },
          teamData: {
            show: false
          },
          myHeaders: {authorization: ''},
          contractStatusData: [], //合同状态
          fileAction: this.$api.postContractUploadContract, //附件上传地址
          file: [],
          fileList: [], //附件url
          productData: { //产品
            slectData: [],
            show: false
          },
          kehuData: [],
          sellData: [],
          trendsTypeData: [], //动态类型
          rules: {
            customerId: [{ required: true, message: '请选择客户', trigger: ['change','blur' ]}],
            contacts: [{ required: true, message: '请输入联系人', trigger: ['change','blur' ]}],
            partyA: [{ required: true, message: '请选择甲方', trigger: 'change' }],
            partyB: [{ required: true, message: '请选择乙方', trigger: 'change' }],
            sellerId: [{ required: true, message: '请选择销售代表', trigger: 'change' }],
            contractSourceType: [{ required: true, message: '请选择合同来源', trigger: 'blur' }],
            signingDate: [{ type: 'date', required: true, message: '请选择签约日期', trigger: 'change' }],
            contactMobile: [{ required: true, message: '必填', trigger: 'change' }],
            artificialPerson: [{ required: true, message: '必填', trigger: 'change' }],
            artificialPersonMobile: [{ required: true, message: '必填', trigger: 'change' }],
            accountantId: [ //会计
                { validator: (rule, value, callback) => {
                    if (value == '' && this.parames.contractStatus == 'SINGED'  && (this.productType == 2 || this.productType == 1)) { //代理记账会计必填
                        callback(new Error('必填'));
                    } else {
                        callback()
                    }
                }, trigger: 'blur' }
            ],
            handlerId: [ //办理人
                { validator: (rule, value, callback) => {
                    if (value == '' && this.parames.contractStatus == 'SINGED'  && (this.productType == 3 || this.productType == 1)) { //代理记账会计必填
                        callback(new Error('必填'));
                    } else {
                        callback()
                    }
                }, trigger: 'blur' }
            ],
          },
          companyData: [], //企业类型
          contactType: [], //联系方式
          tableData: [],
          detailData: {
            id: '',
            show: false
          },
          productType: '',
          groupListta: [], //产品组合
        };
    },
    created() {
    },
    mounted() {
      this.getPhoneType()
    },
    methods: {
      watchSlect (data) { //监听返回的选中的数组
        let select = data //选中的数组
        let origan = this.parames.contractProductList //本身存在的数组
        this.parames.contractProductList = []
        select.forEach(el=>{
          this.parames.contractProductList.push({
            productId: el.productId,
            productName: el.productName,
            upperPriceLimit: el.upperPriceLimit,
            lowerPriceLimit: el.lowerPriceLimit,
            count: el.count?el.count:1,
            discount: el.discount?el.discount:0,
            giftCount: el.giftCount?el.giftCount:0,
            productServiceType: el.productServiceType?el.productServiceType:'',
            unitPrice: el.unitPrice?el.unitPrice:0,
          })
        })
        origan.forEach((el,index)=>{
          this.parames.contractProductList.forEach(bl=>{
            if(el.productId == bl.productId) {
              if (el.id) { //修改合同-合同产品本身存在的id
                bl.id = el.id
              }
              bl.count = el.count
              bl.discount = el.discount
              bl.giftCount = el.giftCount
              bl.unitPrice = el.unitPrice
            }
          })
        })
        // 选中的值和产品组合匹配勾选问题
        this.groupListta.forEach(el=>{
          let oData = []
          el.productList.forEach(bl=>{ //bl循环的数组组合
            this.parames.contractProductList.forEach(cl=>{ //cl当前点击的数组组合
              if (bl.id == cl.productId) {
                oData.push(bl)
              }
            })
            if ((oData.length == el.productList.length)) {
              el.isSelect = true
            }
          })
        })
      },
      changeCustomer () { //新建-选择客户带出客户的联系人-商机数据
        if (this.dialogData.type == 'new') {
          this.parames.contractProductList = []
          this.$post(this.$api.postOpportunityProductListByCustomer,{
            customerId: this.parames.customerId,
          }).then(response => {
            if (response.data.succeed) {
              if (response.data.data.contacts) {
                this.parames.contacts = response.data.data.contacts
              }
              if (response.data.data.contactType) {
                this.parames.contactType = response.data.data.contactType.name
              }
              if (response.data.data.mobile) {
                this.parames.contactDetails = response.data.data.mobile
              }
              response.data.data.opportunityProductList.forEach(el=>{
                this.parames.contractProductList.push({
                  productId: el.productId,
                  productName: el.productName,
                  count: el.count,
                  discount: el.discount,
                  giftCount: el.giftCount,
                  productServiceType: el.productServiceType,
                  unitPrice: el.unitPrice,
                  upperPriceLimit: el.upperPriceLimit,
                  lowerPriceLimit: el.lowerPriceLimit,
                })
              })
              this.groupListta.forEach(el=>{ //快速添加是否是选中
                let oData = []
                el.productList.forEach(bl=>{ //bl循环的数组组合
                  this.parames.contractProductList.forEach(cl=>{ //当前所有已选产品
                    if (bl.id == cl.productId) {
                      oData.push(bl)
                    }
                  })
                  if (oData.length == el.productList.length) {
                    el.isSelect = true
                  }
                })
              })
            }
          })
        }
      },
      handleBack () { //商机转合同-返回商机详情
        this.$emit('checkOpen')
        this.handleClose()
      },
      handleNewTeam () { //添加新成员
        this.teamData.show = true
      },
      selectUser (value) { //添加选择的成员
        if (this.dialogData.type == 'new' || this.dialogData.type == 'tranes' || this.dialogData.type == 'editAgain') {
          let select = value //选中的数组
          let origan = this.parames.userIdList //本身存在的数组
          select.forEach(el=>{
            let i = 0
            origan.forEach((bl,index)=>{
              if (el.userId == bl.userId) {
                i = 1
              }
            })
            if (i !== 1) {
              this.parames.userIdList.push(el)
            }
          })
        } else {
          let select = value //选中的数组
          let userIdList = []
          let origan = this.parames.userIdList //本身存在的数组
          select.forEach(el=>{
            let i = 0
            origan.forEach((bl,index)=>{
              if (el.userId == bl.userId) {
                i = 1
              }
            })
            if (i !== 1) {
              userIdList.push(el.userId)
            }
          })
          this.$post(this.$api.postOpportunityTeamMemberAdd,{
            teamId: this.dialogData.id,
            userIdList: userIdList
          }).then(response => {
            if (response.data.succeed) {
              this.render()
            }
          })
        }
      },
      handleDeleteUser (index,item) { //删除组内人员
        if (item.teamMemberId) {
          this.$post(this.$api.postOpportunityTeamMemberDel,{
            teamMemberId: item.teamMemberId
          }).then(response => {
            if (response.data.succeed) {
              this.$message({ type:'success',message: '删除成功'})
              this.parames.userIdList.splice(index,1)
            }
          })
        } else {
          this.parames.userIdList.splice(index,1)
        }
      },
      getKehu() { //获取客户下拉数据
        this.$post(this.$api.postCustomerCoreListForContract).then(response => {
          if (response.data.succeed) {
              this.kehuData = response.data.data
          }
        })
      },
      getMaifang () { //获取卖方数据
        this.$post(this.$api.postProviderList).then(response => {
          if (response.status == 200) {
              this.sellData = response.data.data
          }
        })
      },
      handelAddProduct () { //添加产品
        this.productData.slectData = this.parames.contractProductList
        this.productData.show = true
      },
      handleSucess (response,fileList) { //上传附件成功返回url
        this.fileList.push({
            name: response.data.name,
            url: response.data.url
        })
      },
      handleRemove (file) { //删除附件更新
        this.fileList.forEach((el,index)=>{
            if (file.response) {
                if (el.url == file.response.data.url) {
                    this.fileList.splice(index, 1)
                }
            } else {
                if (el == file.url) {
                    this.fileList.splice(index, 1)
                }
            }
            
        })
      },
      handleDelproduct (index,row) { //删除当前行产品
        // if (row.id) {
        //   this.$post(this.$api.postContactProductDel,{
        //     contractProductId: row.id
        //   }).then(response => {
        //     this.parames.contractProductList.splice(index,1)
        //   })
        // } else {
          
        // }
        this.parames.contractProductList.splice(index,1)
        this.groupListta.forEach(el=>{
          el.productList.forEach(bl=>{
            if (row.productId == bl.id) {
              el.isSelect = false
            }
          })
        })
      },
      checkValue (value) { //合同来源获取信息
        this.parames.contractSourceType = value
      },
      getSummaries(param) { //产品合计
        const { columns, data } = param;
        const sums = [];
        let values = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          // let values = data.map(item => Number(item[column.property]));

          if (column.property == 'unitPrice') {
            values = data.map(item => Number(item.unitPrice * item.count-item.discount))
          }
          if (index == 7) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '.00';
          } else {
            sums[index] = '';
          }
        });
        return sums;
      },
      setData () {
        let userIdList = []
        this.parames.userIdList.forEach(el=>{
          userIdList.push(el.userId)
        })
        this.parames.userIdList = userIdList
        if (this.parames.contractProductList) { //处理合同产品
          this.parames.contractProductList.forEach(el=>{
            el.contractProductStatus = ''
            if (el.productUnit) {
              el.productUnit = ''
            }
            if (el.productServiceType) {
               el.productServiceType = ''
            }
            if (el.paymentStatus) {
              el.paymentStatus = ''
            }
          })
        }
        this.parames.attachmentSet = this.fileList
      },
      handleProductType () { //判断选择产品的3种情况
      return false
        if (this.parames.contractProductList) { //处理合同产品
          let one = 0
          let jizhang = 0
          this.parames.contractProductList.forEach(el=>{
            if (el.productServiceType) {
              if (el.productServiceType.name == 'BOOK_KEEPING') {
                jizhang = 1
              }
              if (el.productServiceType.name == 'DISPOSABLE') {
                one = 1
              }
            }
          })
          if (jizhang == 1 && one == 1) {
            this.productType = 1 //既有记账也有一次性
          } else if (jizhang == 1 && one == 0) {
            this.productType = 2 //有记账
          } else if (jizhang == 0 && one == 1) {
            this.productType = 3 //有一次性
          }
        }
      },
      handleSave () { //保存合同
        this.handleProductType()
        this.$refs['parames'].validate((valid) => {
          if (valid) {
            this.setData()
            if (this.parames.contractProductList.length == 0) {
              this.$message.error('请录入产品数据');
              return false
            }
            let n = 0
            this.parames.contractProductList.forEach(el=>{
              if (el.discount<0 || (el.discount>(el.count*el.unitPrice))) {
                n = 1
              }
            })
            if (n == 1) {
              this.$message.error('合同产品优惠金额输入不正确');
              return false
            }
            this.loading = true
            if (this.dialogData.type == 'edit') { //修改保存成功
              this.$post(this.$api.postContactEdit,this.parames).then(response => {
                if (response.data.succeed) {
                  this.$message({ type:'success',message: '修改成功'})
                  this.handleClose()
                  this.$emit('checkOpen','1') //重新打开父级弹窗
                }
              })
            } else { //新增
              this.$post(this.$api.postContactAdd,this.parames).then(response => {
                if (response.data.succeed) {
                  this.$message({ type:'success',message: '保存成功'})
                  if (this.dialogData.type == 'editAgain') { //续签合同
                    this.$emit('checkOpen','3') //刷新列表关闭弹窗
                  }
                  if (this.dialogData.type == 'tranes') { //商机转化为合同
                    this.$emit('checkOpen','2') //刷新列表关闭弹窗
                  }
                  this.$emit('checkRender')
                  this.handleClose()
                }
              })
            }
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      handleClose () { //关闭弹窗
        this.dialogData.show = false
      },
      handleCancle () { //取消重新编辑
        this.dialogData.show = false
        this.$emit('checkOpen','4')
      },
      getPhoneType () { //获取联系方式
        this.$post(this.$api.postContactType).then(response => {
          if (response.data.succeed) {
            this.contactType = response.data.data
          }
        })
      },
      postProductGroupList () { //获取所有产品组合
        this.$post(this.$api.postProductGroupList).then(response => {
            if (response.data.succeed) {
              response.data.data.forEach(el=>{
                el.isSelect = false
              })
              this.groupListta = response.data.data
            }
        })
      },
      handleTags (item,index) { //点击产品组合
        item.isSelect = !item.isSelect
        let origin = item.productList
        if (item.isSelect) { //添加
          let newArr = []
          origin.forEach(el => {
            newArr.push({
              productId: el.id,
              productName: el.productName,
              // productUnit: el.productUnit,
              count: el.count?el.count:1,
              discount: el.discount?el.count:0,
              giftCount: el.giftCount?el.giftCount:0,
              productServiceType: el.productServiceType,
              upperPriceLimit: el.upperPriceLimit,
              lowerPriceLimit: el.lowerPriceLimit,
              unitPrice: el.unitPrice?el.unitPrice:0,
            })
          })
          var arr3 = this.$utils.unique2(newArr.concat(this.parames.contractProductList),'productId')
          this.watchSlect(arr3)
          // 选中时如果点击的产品组合的范围包含另外一个产品组合，那么另外一个也要选上
          this.groupListta.forEach(el=>{
            let oData = []
            el.productList.forEach(bl=>{ //bl循环的数组组合
              origin.forEach(cl=>{ //cl当前点击的数组组合
                if (bl.id == cl.id) {
                  oData.push(bl)
                }
              })
              if ((oData.length == el.productList.length) && el.id !== item.id) {
                el.isSelect = true
              }
            })
          })
        } else { //删除
          origin.forEach(bl => {
            for(let i=this.parames.contractProductList.length-1;i>=0;i--){
              if(this.parames.contractProductList[i].productId === bl.id){
                this.parames.contractProductList.splice(i,1);
              }
            }
          })
          // 取消选中时如果点击的产品组合的范围包含另外一个产品组合，那么另外一个也要选上
          this.groupListta.forEach(el=>{
            let oData = []
            el.productList.forEach(bl=>{ //bl循环的数组组合
              origin.forEach(cl=>{ //cl当前点击的数组组合
                if (bl.id == cl.id) {
                  oData.push(bl)
                }
              })
              if (oData.length>0) {
                el.isSelect = false
              }
            })
          })
        }
      },
      render () { //获取详情信息
        this.loading = true
        this.$post(this.$api.postContactFind,{
          contractId: this.dialogData.id
        }).then(response => {
          if (response.data.succeed) {
            let data = response.data.data
            this.parames.id = data.id
            // this.parames.contractNumber = data.contractNumber
            this.parames.customerId = data.customerId
            this.parames.contacts = data.contacts
            if (data.contractStatus) {
              this.parames.contractStatus = data.contractStatus.name
            }
            if (data.contractType) {
              this.parames.contractType = data.contractType.name  //合同类型
            }
            this.parames.contactDetails = data.contactDetails
            if (data.contactType) {
              this.parames.contactType = data.contactType.name
            }
            this.parames.partyA = data.partyA
            this.parames.partyB = data.partyB
            this.parames.opportunity = data.opportunity
            if (this.parames.contractSourceType !== null) {
              this.parames.contractSourceType = data.contractSourceType.name
            }
            if (data.enterpriseType) {
              this.parames.enterpriseType = data.enterpriseType.name
            }
            if (data.opportunityId) { //商机id
              this.parames.opportunityId = data.opportunityId
            }
            this.parames.invoice = data.invoice //是否开发票
            this.parames.startDate = data.startDate//合同开始日期
            this.parames.endDate = data.endDate//合同结束日期
            this.parames.contactMobile = data.contactMobile//联系电话
            this.parames.artificialPerson = data.artificialPerson //法人
            this.parames.artificialPersonMobile = data.artificialPersonMobile //法人电话
            this.parames.accountantId = data.accountantId//会计ID
            this.parames.handlerId = data.handlerId //办理人ID
            this.parames.contractSourceId = data.contractSourceId
            this.parames.sellerId = data.sellerId
            this.parames.signingDate = data.signingDate
            this.parames.contractRemark = data.contractRemark
            this.parames.contractProductList = data.contractProductList
            this.parames.userIdList = data.teamMemberList
            this.parames.renew = data.renew
            if (this.dialogData.type == 'editAgain') {
              this.parames.contractProductList.forEach(el=>{
                el.id = ''
                el.contractId = ''
              })
              this.parames.renew = true
            }
            this.fileList = data.attachmentSet
            data.attachmentSet.forEach(el=>{
                this.file.push({
                    name: el.name,
                    url: el.url
                })
            })
            // 选中的值和产品组合匹配勾选问题
            setTimeout(() => {
              this.groupListta.forEach(el=>{
                let oData = []
                el.productList.forEach(bl=>{ //bl循环的数组组合
                  this.parames.contractProductList.forEach(cl=>{ //cl当前点击的数组组合
                    if (bl.id == cl.productId) {
                      oData.push(bl)
                    }
                  })
                  if ((oData.length == el.productList.length)) {
                    el.isSelect = true
                  }
                })
              })
            }, 200)
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      render2 () {
        this.$post(this.$api.postOpportunityFind,{ //根据id获取详情商机数据并把部分值赋值给合同数据
          opportunityId: this.dialogData.sjId
        }).then(response => {
          if (response.data.succeed) {
            let data = response.data.data
            this.parames.customerId =  data.customerId //客户id
            this.parames.contacts = data.contacts //联系人,
            if (data.contactType) {
              this.parames.contactType = data.contactType.name  //联系方式类型
            }
            this.parames.contactDetails = data.mobile //联系
            if (data.opportunitySourceType) {
              this.parames.contractSourceType = data.opportunitySourceType.name
            }
            this.parames.opportunityId = this.dialogData.sjId
            this.parames.contractSourceId = data.opportunitySourceId //来源id
            this.parames.contractProductList = []
            data.opportunityProductList.forEach(el=>{
              this.parames.contractProductList.push({
                productId: el.productId,
                productName: el.productName,
                count: el.count,
                discount: el.discount,
                giftCount: el.giftCount,
                productServiceType: el.productServiceType,
                upperPriceLimit: el.upperPriceLimit,
                lowerPriceLimit: el.lowerPriceLimit,
                unitPrice: el.unitPrice,
              })
            })
            this.groupListta.forEach(el=>{ //快速添加是否是选中
              let oData = []
              el.productList.forEach(bl=>{ //bl循环的数组组合
                this.parames.contractProductList.forEach(cl=>{ //当前所有已选产品
                  if (bl.id == cl.productId) {
                    oData.push(bl)
                  }
                })
                if (oData.length == el.productList.length) {
                  el.isSelect = true
                }
              })
            })
            this.parames.userIdList =  data.teamMemberList
            setTimeout(() => {
              this.parames.sellerId = this.$utils.getLocalStorage('user').id
              this.parames.signingDate = new Date()
            }, 200);
          }
        })
      },
      resetData () { //关闭弹窗重置所有数据
        this.parames.id = ''
        this.loading = false
        // this.parames.contractNumber = ''
        this.parames.customerId = ''
        this.parames.contacts = ''
        this.parames.contractStatus = 'PENDING'
        this.parames.contractType = ''
        this.parames.contactType = ''
        this.parames.contactDetails = ''
        this.parames.partyA = ''
        this.parames.partyB = ''
        this.parames.opportunity = ''
        this.parames.contractSourceType = ''
        this.parames.contractSourceId = ''
        this.parames.sellerId = ''
        this.parames.signingDate = ''
        this.parames.contractRemark = ''
        this.parames.opportunityId = ''
        this.parames.enterpriseType = ''
        this.parames.invoice = false //是否开发票
        this.parames.startDate = '' //合同开始日期
        this.parames.endDate = '' //合同结束日期
        this.parames.contactMobile = '' //联系电话
        this.parames.artificialPerson = '' //法人
        this.parames.artificialPersonMobile = '' //法人电话
        this.parames.accountantId = '' //会计ID
        this.parames.handlerId = '' //办理人ID
        this.parames.attachmentSet = []
        this.parames.renew = false
        this.file = []
        this.fileList = []
        this.$refs.parames.resetFields()
        this.parames.contractProductList = []
        this.parames.userIdList = []
      }
    },
    components: {
      productDialog
    },
    computed: {
      changeDialog () {
        return this.dialogData.show
      }
    }, 
    watch: {
      changeDialog: {
        handler (curVal, oldVal) {
          if (curVal) {
            this.myHeaders.authorization = this.$utils.getLocalStorage('usertoken')
            this.postProductGroupList()
            let userInfo = this.$utils.getLocalStorage('user')
            if (this.dialogData.type == 'new') {
              this.parames.userIdList.push({
                userName: userInfo.name,
                userId: userInfo.id
              })
              setTimeout(() => {
                this.parames.signingDate = new Date()
                this.parames.sellerId = this.$utils.getLocalStorage('user').id
              }, 200);
            }
            this.$utils.getEnumberation('postContractStatus','contractStatusData',this) //合同状态
            this.$utils.getEnumberation('postContactEnterpriseType','companyData',this) //企业类型
            this.getPhoneType()
            this.getKehu()
            this.getMaifang()
            if (this.dialogData.type == 'edit' || this.dialogData.type == 'editAgain') {
              this.render()
            }
            if (this.dialogData.type == 'tranes') { //从商机转化为合同
              this.render2()
            }
            
          } else {
            this.resetData()
          }
        }
      }
    },
};
</script>

<style scoped>
.tab-cur {
 background: url() no-repeat 100% 100%;
}
</style>
